<template>
	<div class="login_background">
		<div class="login_background_front"></div>
		<div class="login_main">
			<div class="login-form">
				<div class="login-p">
					<UiwQrcodeLogin class="QRcodeIcon" @click="swichLoginType(1)" v-if="loginType == 'NORMAL'" />
					<UiwUser class="QRcodeIcon" @click="swichLoginType(2)" v-else />
					<a-card>
						<div class="login-header">
							<div class="logo">
								<img :alt="sysBaseConfig.SNOWY_SYS_NAME" :src="sysBaseConfig.SNOWY_SYS_LOGO" />
								<label>{{ sysBaseConfig.SNOWY_SYS_NAME }}</label>
							</div>
							<!--<h2>{{ $t('login.signInTitle') }}</h2>-->
						</div>
						<a-tabs v-model:activeKey="activeKey" v-if="loginType == 'NORMAL'">
							<a-tab-pane key="ACCOUNT" :tab="$t('login.accountPassword')">
								<a-form ref="loginForm" :model="ruleForm" :rules="rules">
									<a-form-item name="userAccount">
										<a-input
											v-model:value="ruleForm.userAccount"
											:placeholder="$t('login.accountPlaceholder')"
											size="large"
											@keyup.enter="login"
										>
											<template #prefix>
												<UserOutlined class="login-icon-gray" />
											</template>
										</a-input>
									</a-form-item>
									<a-form-item name="password">
										<a-input-password
											v-model:value="ruleForm.password"
											:placeholder="$t('login.PWPlaceholder')"
											size="large"
											autocomplete="off"
											@keyup.enter="login"
										>
											<template #prefix>
												<LockOutlined class="login-icon-gray" />
											</template>
										</a-input-password>
									</a-form-item>
									<a-form-item name="validCode" v-if="captchaOpen === 'true'">
										<a-row :gutter="8">
											<a-col :span="17">
												<a-input
													v-model:value="ruleForm.validCode"
													:placeholder="$t('login.validLaceholder')"
													size="large"
													@keyup.enter="login"
												>
													<template #prefix>
														<verified-outlined class="login-icon-gray" />
													</template>
												</a-input>
											</a-col>
											<a-col :span="7">
												<img :src="validCodeBase64" class="login-validCode-img" @click="loginCaptcha" />
											</a-col>
										</a-row>
									</a-form-item>

									<a-form-item>
										<a href="/findpwd" style="color: #0d84ff">{{ $t('login.forgetPassword') }}？</a>
									</a-form-item>
									<a-form-item>
										<a-button type="primary" class="w-full" :loading="loading" round size="large" @click="login"
											>{{ $t('login.signIn') }}
										</a-button>
									</a-form-item>
								</a-form>
							</a-tab-pane>
							<a-tab-pane key="PHONE" :tab="$t('login.phoneSms')" force-render>
								<phone-login-form />
							</a-tab-pane>
						</a-tabs>
						<a-tabs v-else>
							<a-tab-pane tab="扫码登陆">
								<div><info-circle-outlined style="color: red" /><span>5分钟失效</span></div>
								<img :src="gzhQrUrl" alt="" style="width: 260px; margin-left: 24px" />
							</a-tab-pane>
						</a-tabs>
						<!-- <three-login /> -->
					</a-card>
				</div>
			</div>
		</div>
	</div>
</template>
<script setup>
import { onMounted, onUnmounted } from 'vue'
import loginApi from '@/api/auth/loginApi'
import thirdApi from '@/api/auth/thirdApi'
import PhoneLoginForm from './phoneLoginForm.vue'
import ThreeLogin from './threeLogin.vue'
import smCrypto from '@/utils/smCrypto'
import { required } from '@/utils/formRules'
import { afterLogin } from './util'
import configData from '@/config'
import tool from '@/utils/tool'
import { globalStore, iframeStore, keepAliveStore, viewTagsStore } from '@/store'
const { proxy } = getCurrentInstance()

const gzhQrUrl = ref('')
const gzhQrKey = ref('')
const timer = ref()
const loginType = ref('NORMAL')
const activeKey = ref('ACCOUNT')
const captchaOpen = ref(configData.SYS_BASE_CONFIG.SNOWY_SYS_DEFAULT_CAPTCHA_OPEN)
const validCodeBase64 = ref('')
const loading = ref(false)

const ruleForm = reactive({
	userAccount: 'superAdmin',
	password: '123abc',
	validCode: '',
	validCodeReqNo: '',
	autologin: false
})

const rules = reactive({
	account: [required(proxy.$t('login.accountError'), 'blur')],
	password: [required(proxy.$t('login.PWError'), 'blur')]
})
const lang = ref([
	{
		name: '简体中文',
		value: 'zh-cn'
	},
	{
		name: 'English',
		value: 'en'
	}
])
const config = ref({
	lang: tool.data.get('APP_LANG') || proxy.$CONFIG.LANG,
	theme: tool.data.get('APP_THEME') || 'default'
})

const store = globalStore()
const kStore = keepAliveStore()
const iStore = iframeStore()
const vStore = viewTagsStore()

const setSysBaseConfig = store.setSysBaseConfig
const clearKeepLive = kStore.clearKeepLive
const clearIframeList = iStore.clearIframeList
const clearViewTags = vStore.clearViewTags

const sysBaseConfig = computed(() => {
	return store.sysBaseConfig
})

onMounted(() => {
	let formData = ref(configData.SYS_BASE_CONFIG)
	const host = window.location.hostname
	loginApi.getTenantSiteInfoByHost(host).then((data) => {
		if (data) {
			console.log(data)
			formData.value = data
			// data.forEach((item) => {
			// 	formData.value[item.configKey] = item.configValue
			// })
			// captchaOpen.value = formData.value.SNOWY_SYS_DEFAULT_CAPTCHA_OPEN
			// tool.data.set('SNOWY_SYS_BASE_CONFIG', formData.value)
			// setSysBaseConfig(formData.value)
			refreshSwitch()
		}
	})
})

onBeforeMount(() => {
	clearViewTags()
	clearKeepLive()
	clearIframeList()
})

// 监听语言
watch(
	() => config.value.lang,
	(newValue) => {
		proxy.$i18n.locale = newValue
		tool.data.set('APP_LANG', newValue)
	}
)
// 主题
watch(
	() => config.value.theme,
	(newValue) => {
		document.body.setAttribute('data-theme', newValue)
	}
)
// 通过开关加载内容
const refreshSwitch = () => {
	// 判断是否开启验证码
	if (captchaOpen.value === 'true') {
		// 加载验证码
		loginCaptcha()
		// 加入校验
		rules.validCode = [required(proxy.$t('login.validError'), 'blur')]
	}
}

// 获取验证码
const loginCaptcha = () => {
	loginApi.getPicCaptcha().then((data) => {
		validCodeBase64.value = data.captchaBase64
		ruleForm.validCodeReqNo = data.captchaCode
	})
}
//登陆
const loginForm = ref()
const login = async () => {
	loginForm.value.validate().then(async () => {
		loading.value = true
		const loginData = {
			userAccount: ruleForm.userAccount,
			// 密码进行SM2加密，传输过程中看到的只有密文，后端存储使用hash
			password: smCrypto.doSm2Encrypt(ruleForm.password),
			validCode: ruleForm.validCode,
			validCodeReqNo: ruleForm.validCodeReqNo,
			loginType: activeKey.value
		}
		// 获取token
		try {
			const loginRetData = await loginApi.login(loginData)
			if (!loginRetData) {
				loading.value = false
				return
			}
			afterLogin(loginRetData)
		} catch (err) {
			loading.value = false
			loginCaptcha()
		}
	})
}
const swichLoginType = (type) => {
	if (type === 1) {
		thirdApi
			.gzhQrUrl()
			.then((data) => {
				console.log(data)
				if (data) {
					gzhQrUrl.value = data.captchaBase64
					gzhQrKey.value = data.captchaCode
					loginType.value = ''
					clearInterval(timer)
					timer.value = setInterval(() => {
						thirdApi.gzhQrCheck(gzhQrKey.value).then((loginRetData) => {
							console.log(loginRetData)
							if (loginRetData) {
								if (!loginRetData) {
									loading.value = false
									return
								}
								afterLogin(loginRetData)
							}
						})
					}, 1000 * 10)
				} else {
				}
			})
			.catch((e) => {})
	} else {
		loginType.value = 'NORMAL'
	}
}
const configLang = (key) => {
	config.value.lang = key
}

onUnmounted(() => {
	clearInterval(timer.value)
	timer.value = null
})
</script>
<style lang="less" scoped>
@import 'login';
.ant-card {
	background: transparent !important;
	padding: 0px !important;
}
.ant-card-body {
	padding: 0px !important;
}
.ant-card-bordered {
	border: 0px !important;
}
.login-p {
	background: #ffffff;
	padding: 24px;
	border: 1px solid var(--border-color-split);
}
.QRcodeIcon {
	width: 40px;
	height: 40px;
	position: absolute;
	right: 0;
	font-size: 32px;
	color: #1890ff;
	margin-top: -20px;
	margin-right: 4px;
}
</style>
